package array.leetcode.easy;

/**
 * @author bruin_du
 * @description 顺时针打印矩阵
 * @date 2022/6/13 22:55
 **/
public class Offer29_SpiralOrder {
    public int[] spiralOrder(int[][] matrix) {
        if(matrix.length == 0) return new int[0];
        int[] ret = new int[matrix.length * matrix[0].length];
        int up = 0,down = matrix.length - 1;
        int left = 0,right = matrix[0].length - 1;
        int index = 0;
        while(up <= down && left <= right){
            for (int i = left; i <= right; i++) {
                ret[index++] = matrix[up][i];
            }
            if(++up > down) break;
            for (int i = up; i <= down; i++) {
                ret[index++] = matrix[i][right];
            }
            if(left > --right) break;
            for (int i = right; i >= left; i--) {
                ret[index++] = matrix[down][i];
            }
            if(up > --down) break;
            for (int i = down; i >= up; i--) {
                ret[index++] = matrix[i][left];
            }
            if(++left > right) break;
        }
        return ret;
    }
}
